/**
 * 先输出员工模式下的包在输出集团模式下的包
 */
const childProcess = require("child_process");
const fs = require("fs");
const path = require("path");

const { readFileSync, existsSync, readdirSync, statSync, unlinkSync, rmdirSync, writeFileSync } = fs;
const { resolve, join } = path;
const { exec, execSync } = childProcess;

const menuRoute = resolve(__dirname, '../src/routes');
const menuPath = resolve(__dirname,'../src/routes/menuRoute.js');

let fileContent = readFileSync(menuPath,'utf-8');

let copyFile = fileContent;

/**
 * 删除文件夹
 * @param path 文件夹路径
 */
function deleteFolder(path) {
  var files = [];
  if( existsSync(path) ) {
    files = readdirSync(path);
    files.forEach(function(file){
      var curPath = path + "/" + file;
      if(statSync(curPath).isDirectory()) { // recurse
        deleteFolder(curPath);
      } else { // delete file
        unlinkSync(curPath);
      }
    });
    rmdirSync(path);
  }
}

function handleMenu(isNormal) {
  let content = fs.readFileSync(menuPath,'utf-8');
  let reg = new RegExp('const menu = \\[([^\\]]+)\\]','g');
  let invalidContent = '';
  let invalidKey = [];
  content = content.replace(reg,(target,$1) => {
    $1 = $1.split('/** 以下是管理员模式下的菜单 **/');
    if(isNormal){
      invalidContent = $1[1];
      $1 = $1[0];
      target = `const menu = [${$1}]`;
    } else {
      invalidContent = $1[0];
      $1 = $1[1];
      target = `const menu = [${$1}]`;
    }
    return target;
  });
  let comReg = new RegExp('([a-zA-Z]+)(\\s)*(,)?(\\s)*(//[^\n]+[\n])?','g');
  invalidContent = invalidContent.replace(comReg,(tar,f1) => {
    invalidKey.push(f1);
    return tar;
  });
  let importReg = new RegExp('import(\\s)*([a-zA-Z]+)(\\s)*from(\\s)*(\'|")([^\'"]+)(\'|")(;)?','mg');
  content = content.replace(importReg,(target,$1,$2) => {
    if(invalidKey.indexOf($2) > -1){
      target = '';
    }
    return target;
  });
  writeFileSync(menuPath,content);
}

function userMode(isNormal){
  deleteFolder(join(menuRoute,isNormal ? 'admin' : 'normal'));
  handleMenu(isNormal);
}

userMode(process.argv[2] === 'user');
